package org.atlantis.nio;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;

/**
 * 通过内存映射文件来实现JVM进程通信。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">李曦</a><br/>
 *         $Created at: 2012-2-23 下午8:35:42
 */
public class ReadShareMemory {

	// 共享文件的大小
	private static final int SHARE_SIZE = 1024;

	public static void main(String[] args) throws Exception {
		RandomAccessFile shareFile = new RandomAccessFile("F:/share_swap.mm", "rw");
		MappedByteBuffer share = shareFile.getChannel().map(MapMode.READ_WRITE, 0, SHARE_SIZE);

		int lastIndex = 0;
		for (int i = 0; i < 27; i++) {
			int flag = share.get(0); // 获取读写数据的标识
			int index = share.get(1);
			if (flag != 2 || index == lastIndex) { // 如果不可读，或未写入新数据时，循环等待
				i--;
				continue;
			}

			lastIndex = index;
			System.out.println("读取数据：" + (char) share.get(index));
			share.put(0, (byte) 0);
		}
	}
}
